<template>
  <el-card>
    <el-button type="primary" size="default" icon="Plus" @click="addTrademark">
      添加品牌
    </el-button>

    <el-table
      stripe
      border
      style="width: 100%; margin: 10px 0px"
      :data="trademarkArr"
    >
      <el-table-column
        prop="id"
        label="序号"
        width="80px"
        align="center"
        type="index"
      />

      <el-table-column
        prop="logoUrl"
        label="LOGO"
        header-align="left"
        width="180px"
      >
        <template #="{ row }">
          <el-image
            :src="row.logoUrl"
            alt="^"
            style="width: 50px; height: 50px"
          ></el-image>
        </template>
      </el-table-column>

      <el-table-column prop="tmName" label="品牌名称" header-align="left">
        <template #="{ row }">
          <pre style="color: rgb(56, 44, 44)">{{ row.tmName }}</pre>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="操作" header-align="left" width="180px">
        <template #="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateTrademark(row)"
          ></el-button>

          <el-popconfirm
            :title="`您确定要删除${row.tmName}吗？`"
            width="280px"
            icon="Delete"
            @confirm="removeTrademark(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="getHasTrademark"
      @size-change="handleSizeChange"
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :pager-count="9"
      :page-sizes="[5, 10, 50, 100]"
      :small="true"
      :background="true"
      layout="prev, pager, next, jumper,->,total, sizes"
      :total="total"
    />
  </el-card>

  <!-- 添加品牌 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="tardemarkParams.id ? '修改品牌' : '添加品牌'"
  >
    <el-form
      :model="tardemarkParams"
      :rules="rules"
      style="width: 80%"
      ref="trademarkForms"
    >
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input
          placeholder="请您输入品牌名称"
          v-model="tardemarkParams.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          method="POST"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="tardemarkParams.logoUrl"
            :src="tardemarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取 消</el-button>
      <el-button type="primary" size="default" @click="confirm">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type {
  Records,
  TrademarkResponseData,
  Trademark,
} from '@/api/product/trademark/type'
import { ElMessage, type UploadProps, FormRules } from 'element-plus'

let pageNo = ref(1)
let pageSize = ref(5)
let total = ref(0)
let trademarkArr = ref<Records>([])
let trademarkForms = ref()

const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager
  let result: TrademarkResponseData = await reqHasTrademark(
    pageNo.value,
    pageSize.value,
  )

  if (result.code === 200) {
    total.value = result.data.total
    pageSize.value = result.data.size
    pageNo.value = result.data.current
    trademarkArr.value = result.data.records
  }
}

onMounted(() => {
  getHasTrademark()
})

const handleSizeChange = () => {
  getHasTrademark()
}

// 编辑对话框
let dialogFormVisible = ref(false)
const addTrademark = () => {
  tardemarkParams.id = undefined
  tardemarkParams.tmName = ''
  tardemarkParams.logoUrl = ''
  dialogFormVisible.value = true

  nextTick(() => {
    trademarkForms.value.clearValidate()
  })
}

const updateTrademark = (row: Trademark) => {
  dialogFormVisible.value = true

  // ES6语法合并对象
  Object.assign(tardemarkParams, row)
  nextTick(() => {
    trademarkForms.value.clearValidate()
  })
}

let tardemarkParams = reactive<Trademark>({
  tmName: '',
  logoUrl: '',
})

const cancel = () => {
  dialogFormVisible.value = false
}

const confirm = async () => {
  await trademarkForms.value.validate()

  let result: any = await reqAddOrUpdateTrademark(tardemarkParams)
  if (result.code === 200) {
    ElMessage.success(tardemarkParams.id ? '修改品牌成功' : '添加品牌成功')
    dialogFormVisible.value = false
    getHasTrademark(tardemarkParams.id ? pageNo.value : 1)
  } else {
    ElMessage.error(tardemarkParams.id ? '修改品牌失败' : '添加品牌失败')
  }
}

// 图片上传成功之前触发
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 或 GIF 格式!')
    return false
  }
  if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('上传图片大小不能超过 4MB!')
    return false
  }
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  _uploadFile,
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  trademarkForms.value.clearValidate('logoUrl')
  tardemarkParams.logoUrl = response.data
}

// rule是规则本身
const validatorTmName = (_rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称长度大于等于2个字符'))
  }
}
const validatorLogoUrl = (_rule: any, value: any, callback: any) => {
  if (value) {
    callback()
  } else {
    callback(new Error('请上传LOGO图片'))
  }
}

let rules = reactive<FormRules<Trademark>>({
  tmName: [
    // {required : true, message: '请输入品牌名称', trigger: 'blur'},
    { required: true, trigger: 'blur', validator: validatorTmName },
  ],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
})

const removeTrademark = async (id: number) => {
  let result = await reqDeleteTrademark(id)
  if (result.code === 200) {
    ElMessage.success('删除成功')

    getHasTrademark(
      trademarkArr.value.length > 0 || pageNo.value === 1
        ? pageNo.value
        : pageNo.value - 1,
    )
  } else {
    ElMessage.error('删除失败')
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
